package com.mh.service;

import com.mh.pojo.GarbageResult;
import com.mh.pojo.StatisticsVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Date:2025/3/15
 * author:zmh
 * description: 业务统计相关接口
 **/

@Service
@RequiredArgsConstructor
@Slf4j
public class StatisticalService {

    private final MongoTemplate mongoTemplate;

    // 新增文档
    public GarbageResult save(GarbageResult entity) {
        return mongoTemplate.insert(entity);
    }

    // 根据ID删除
    public void deleteById(String id) {
        mongoTemplate.remove(new Query(Criteria.where("_id").is(id)), GarbageResult.class);
    }

    // 更新文档
//    public GarbageResult update(GarbageResult entity) {
//        Update update = new Update()
//                .set("result", entity.getResult())
//                .set("extraInfo", entity.getExtraInfo())
//                .set("item", entity.getItem())
//                .set("state", entity.getState());
//        mongoTemplate.updateFirst(
//                new Query(Criteria.where("_id").is(entity.getId())),
//                update,
//                GarbageResult.class
//        );
//        return mongoTemplate.findById(entity.getId(), GarbageResult.class);
//    }

    // 按分类（result）分组统计
    public List<StatisticsVO> countByResult() {
        // 按照 result 字段分组，并统计每个 result 的数量
        GroupOperation groupByResult = Aggregation.group("result")
                .count().as("value");

        // 聚合查询
        Aggregation aggregation = Aggregation.newAggregation(groupByResult);

        // 执行查询
        AggregationResults<StatisticsVO> results = mongoTemplate.aggregate(aggregation, "garbage_recognition", StatisticsVO.class);

        List<StatisticsVO> mappedResults = results.getMappedResults();

        return results.getMappedResults();
    }

    // 按物品（item）分组统计
    public List<StatisticsVO> countByItem() {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.group("item").count().as("value"),
                Aggregation.project("value").and("_id").as("name"),
                Aggregation.sort(Sort.Direction.DESC, "value")
        );
        // 添加按照value进行降序排序
        AggregationResults<StatisticsVO> results = mongoTemplate.aggregate(
                aggregation,
                GarbageResult.class,
                StatisticsVO.class
        );
        return results.getMappedResults();
    }
}
